# coding=utf-8
import datetime
import os, django

from shareAPI2020TB.settings import log_wade

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()
import random
import re
from BaseWeb import models
import requests
from urllib.parse import urlencode, quote, unquote

'''
"""两个账户类"""
maokoulingClass.py 说明
            class maokouling_ONE():  我的猫口令配置信息
            |
            #根据id获得商品的高佣长链接
            def tblink_get_gaoyong(config):
            |
'''


# 每个人配置一个请求信息，要求账户设置白名单
# pid（mm_账号id_推广渠道id_推广位id）
# mm_memberId_siteId_adzoneId
# mm_28964573_303450418_82851750421
# 每个人配置一个请求信息，要求账户设置白名单
# 利用喵口令工具对象就要传给喵口令一个账户对象，喵口令工具就是一个车，可以有很多的猫来开
class Tools_Miaokouling:
    def __init__(self, WadeMiaoKouLing_OBJ):
        self.jdid = '100008829953'
        self.pid = WadeMiaoKouLing_OBJ.pid
        self.apkey = WadeMiaoKouLing_OBJ.apkey
        self.key_id = WadeMiaoKouLing_OBJ.JDkey_id
        self.tbusername = WadeMiaoKouLing_OBJ.tbusername

    def getLongUrl_By_FakeUrl(self, FakeUrl):
        # 传入别人的淘客链接 或者商品链接，进行转链，换取自己的长连接和短链接
        # 验证是否是unicode编码，如果编码网址错了，就换成另一种
        try:
            url = f'''http://api.web.ecapi.cn/jingdong/doItemCpsUrl?apkey={self.apkey}&materialId={quote(FakeUrl)}&key_id={self.key_id}&chainType=3'''
            print(url)
            itemJson = requests.get(url, timeout=100)
            if itemJson.json()['code'] != 200:
                log_wade.error(msg=itemJson.json())
                raise Exception
        except:
            url = f'''http://api.web.ecapi.cn/jingdong/doItemCpsUrl?apkey={self.apkey}&materialId={FakeUrl}&key_id={self.key_id}&chainType=3'''
            print(url)
            itemJson = requests.get(url, timeout=100)
        print(itemJson.json())
        try:
            self.realItemUrl_shot = itemJson.json()['data']['shortURL']
            self.realItemUrl_long = itemJson.json()['data']['clickURL']
        except Exception as e:
            log_wade.error(msg=f"{itemJson.json()}")
            return "", ""

        del itemJson
        log_wade.error(msg=f"喵口令短链转换API OK")

        return self.realItemUrl_shot, self.realItemUrl_long

    def getjdid(self, shotUrl):

        # 通过短链接获取商品具体信息，包括id，商品名，价格等内容
        url = f'''http://api.web.ecapi.cn/jingdong/getJdUnionItems?apkey={self.apkey}&keyword={quote(shotUrl)}'''
        # print(url)
        itemJson = requests.get(url, timeout=100)
        log_wade.error(itemJson.json())
        # print(int(itemJson.json()['data']['totalCount']))
        try:
            jdid = int(
                itemJson.json()['data']['list'][0]['materialUrl'].replace('item.jd.com/', '').replace('.html', ''))
            shopid = itemJson.json()['data']['list'][0]['shopInfo']['shopId']
            shopname = itemJson.json()['data']['list'][0]['shopInfo']['shopName']
            skuName = itemJson.json()['data']['list'][0]['skuName']
            item_MainImg = itemJson.json()['data']['list'][0]['imageInfo']['imageList'][0]['url']
            item_price = itemJson.json()['data']['list'][0]['priceInfo']['price']
            print('店铺id', jdid, '店铺名称', shopid, '商品id', shopname)
            del itemJson
            log_wade.error(msg=f"喵口令短链接获取商品api运行，OK")
            return jdid, shopid, shopname, skuName, item_MainImg, item_price
        except Exception as e:
            log_wade.error(msg=f"{itemJson.json()}")
            return 10020943460298, 1000090242, '宇宙陨石', '宇宙陨石', 'https://img14.360buyimg.com/n1/jfs/t1/133104/38/8601/233317/5f48fe77E0fdd7ffe/89810e06b1d05a8a.jpg', 9999999
class Tools_QiBo():
    # 企业博客的发帖工具，但是使用必须给工具配备一个企业博客账户obj
    """功能：1、发帖，生成模板"""

    def __init__(self, WadeQiboAccount_OBJ):
        self.username = WadeQiboAccount_OBJ.username
        self.password = WadeQiboAccount_OBJ.password
        self.bokeeName = WadeQiboAccount_OBJ.bokeeName
        self.runStatus = WadeQiboAccount_OBJ.runStatus

    def postQiBo(self, title, content):
        """发帖发帖"""
        try:
            loginUrl = 'http://tefenxiang.blog.bokee.net/usermodule/userManager_quickLogin.do'
            formdata1 = {
                'username': self.username,
                'password': self.password
            }
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
            }
            session = requests.session()
            html1 = session.post(loginUrl, data=formdata1, headers=headers, timeout=10)  # 登录
            print(f'登录状态: {html1.status_code}')

            postContentUrl = f'http://{self.bokeeName}.blog.bokee.net/bloggermodule/blogadmin2_saveblog.do'
            formdata2 = {
                'bokeeName': self.bokeeName,
                'id': '',
                'action': 'saveEntry',
                'title': title,
                'content': content,
                'columnName': '',
                'addType': '值得买',
                'tags': '',
                'brief': '',
                'visibility': '100',  # 公开方式，保持默认
                'commentable': '1',  # 开启评论，保持默认
                'displayControl': '2',  # 摘要模式，保持默认
                'stateNo': '1'  # 状态码，保持默认
            }
            html2 = session.post(postContentUrl, formdata2, headers=headers, timeout=10)
            htmltexts = html2.text
            # log_wade.error(htmltexts)
            # print(htmltexts)

            finderrorpage = re.compile('非常抱歉！你超出使用限制了！')
            result = finderrorpage.findall(htmltexts)

            if result != []:
                log_wade.error('检测html--发帖使用超出限制')
                raise Exception("发帖使用超出限制")  # 真正检测发够了
            print('发布')
            restr = re.compile('<input type="hidden" name="id" value="(\d+)">')
            contentid = restr.findall(htmltexts)

            # 敏感词过滤捕捉
            findMinGanPage = re.compile("你发布的内容可能有敏感信息")
            findMinGanPage_result = findMinGanPage.findall(htmltexts)
            if findMinGanPage_result != []:
                print('发布的内容可能有敏感信息')
                return True  # 虽然是敏感信息了,但是还是发布成功,返回正确True,不在进行下面的组合

            print('发表后的页面id内容是:')
            # print(html2.text)
            print(contentid)  # 可能是空的[]

            if contentid[0] != "0":
                log_wade.error('检测html--成功发布')
            else:
                log_wade.error("淘宝商品可能有错误")
            # 保存发帖链接,发帖标题为json

            return True
        except Exception as e:
            print(e)
            log_wade.error('发布错误结束')
            return False
class Tools_BBS():
    # bbs的发帖工具，但是使用必须给工具配备一个企业博客账户obj
    """功能：1、发帖，生成模板"""

    def __init__(self, WadeBBSAccount_OBJ):
        self.username = WadeBBSAccount_OBJ.username
        self.postUrl = WadeBBSAccount_OBJ.postUrl
        self.fid = WadeBBSAccount_OBJ.fid
        self.discuzName = WadeBBSAccount_OBJ.discuzName
        self.postNum = WadeBBSAccount_OBJ.postNum
        self.runStatus = WadeBBSAccount_OBJ.runStatus

    def postBBS(self, title, content, pinglunList):
        # 格式化评论楼层
        for i in pinglunList:
            content = f'{content}|||{i}'
        # subject=年后发阿凡达案发时发放&message=年后发阿凡达案发时发放&fid=57&username=怎么样评测
        form = {
            'subject': f'{title}'.encode('gbk', errors='ignore'),
            'message': f'{content}'.encode('gbk', errors='ignore'),
            'fid': f'{self.fid}',
            'username': f'{self.username}'.encode('gbk', errors='ignore'),
        }
        html = requests.post(self.postUrl, data=form)
        if html.text == '发布成功':
            return True
        else:
            return False
    # bbs的发帖工具，但是使用必须给工具配备一个企业博客账户obj
    """功能：1、发帖，生成模板"""

class Tools_JiaDian_BBS():
    # bbs的发帖工具，但是使用必须给工具配备一个企业博客账户obj
    """功能：1、发帖，生成模板"""

    def __init__(self, WadeBBSAccount_OBJ):
        self.username = WadeBBSAccount_OBJ.username
        self.postUrl = WadeBBSAccount_OBJ.postUrl
        self.fid = WadeBBSAccount_OBJ.fid
        self.discuzName = WadeBBSAccount_OBJ.discuzName
        self.postNum = WadeBBSAccount_OBJ.postNum
        self.runStatus = WadeBBSAccount_OBJ.runStatus

    # bbs的发帖工具，但是使用必须给工具配备一个企业博客账户obj
    """功能：1、发帖，生成模板"""

    def postBBS(self, title, content, pinglunList):
        #登录和发帖全部操作，发送模板内容，标题
        import random
        import re
        import time

        import requests
        url = """https://www.shoudian.org/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LH6vn&inajax=1

        formhash=4ca09db1&referer=https%3A%2F%2Fwww.shoudian.org%2Fthread-1547072-1-1.html&loginfield=username&username=jmh690616&password=3d68113750c599408981f43b51405a45&questionid=0&answer=&cookietime=2592000
        """
        # try:
        HEADERS = [
            'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362',
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Mozilla/5.0 (Macintosh;U;IntelMacOSX10_6_8;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586',
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.27 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/601.1.27',
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
        ]
        headers = {
            'Accept': 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'User-Agent': random.choice(HEADERS),
            'Connection': 'keep-alive',
            'Host': 'www.shoudian.org',
            'Referer': 'https://www.shoudian.org/',
        }
        session = requests.Session()
        mainHtml = session.get(url=url, headers=headers)
        print(session.headers)
        t = time.time()
        contentURL = "https://www.shoudian.org/forum.php?mod=post&action=newthread&fid=289&extra=&topicsubmit=yes"
        abc = session.get(url='https://www.shoudian.org/forum.php',headers=headers)
        # print(abc.text)
        formhash_Find = re.compile(r'logout&amp;formhash=(.*)">退出</a>')  # 查找数字
        formhash = formhash_Find.findall(abc.text)[0]
        print(formhash)
        form = {
            'formhash': formhash,
            'posttime': int(t),
            'wysiwyg': 1,
            'subject': f'{"xxxx商品名称"}'[0:10],  #goodname
            'checkbox': 0,
            'message': f'{content}',
            'allownoticeauthor': 1,
            'save': '',
            'file': '',
            'uploadalbum': -2,
            'newalbum': '请输入相册名称',
        }

        abc = session.post(url=contentURL, data=form,headers=headers, verify=False)

        #登录和发帖全部操作，发送模板内容，标题  -----End
class Tools_BaseWeb():
    # 本站内容发帖工具
    """功能：1、负责发帖"""

    def __init__(self):
        print('本地网页发布')

    def postBaseWeb(self, title, content,**kwargs):
        log_wade.error("进入发帖函数postBaseWeb")
        category_id = kwargs['category_id']
        # 随机获得作者，数据表有绑定获得由pid和喵口令id，用来发帖
        querySetAuthorList = models.MS_USER.objects.all()
        if not querySetAuthorList:
            models.MS_USER.objects.get_or_create(id=0)
            querySetAuthorList = models.MS_USER.objects.all()
        log_wade.error("发帖标记1")

        querySetAuthor = random.choice(querySetAuthorList)
        log_wade.error("发帖标记2")

        #  标题和tbid querySet
        # 作者 querySetAuthor
        # 内容：htmlContent
        # 评论 ：htmlpinglunList
        # return HttpResponse(f'{htmlContent},{htmlpinglunList}')
        DetailPageQuerySet = models.DetailPage.objects.create(
            tbid='0123456',
            detail_auther=querySetAuthor,
            title=title,
            content=content,
            tags='',
            date = datetime.datetime.now(),
            category_id = category_id,
        )
        log_wade.error("发帖标记3")

        DetailPageQuerySet.save()
        log_wade.error("发帖函数postBaseWeb  OK")


if __name__ == '__main__':
    # 初始化，获取喵口令数据库 配置
    mkl = Tools_Miaokouling
    apkey ='6e39417a-bc77-3d4d-c2ae-0a51f37d2574'
    key_id ='J4765683946244691'
    tbusername='shenhuawade'
    a = mkl.getLongUrl_By_FakeUrl(FakeUrl ="https://item.jd.com/100002608347.html")
    print(a)
